package com.goldfish666.remote_control.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.SocketException;

@Slf4j
@Component
public class SocketHelper {

    private static ServerSocket serverSocket;

    private static DatagramSocket datagramSocket;

    public static ServerSocket getServerSocket() {
        return serverSocket;
    }

    public static void buildServerSocket(int port, int backlog) {
        if (ObjectUtils.isEmpty(serverSocket)) {
            try {
                InetAddress inetAddress = InetAddress.getLocalHost();
                serverSocket = new ServerSocket(port, backlog, inetAddress);
                log.info("创建{}:{}TCP服务器成功。", inetAddress, port);
            } catch (IOException e) {
                log.error("在本地创建端口{}的TCP服务器失败:{}", port, e.getMessage());
            }
        }
    }

    public static DatagramSocket getDatagramSocket() {
        return datagramSocket;
    }

    public static void buildDatagramSocket(int port) {
        try {
            datagramSocket = new DatagramSocket(port);
        } catch (SocketException e) {
            log.error("创建端口{}的UDP服务失败:{}", port, e.getMessage());
        }
    }
}
